package com.jie.component.filter.wrapper;

import com.jie.common.util.InputStreamUtil;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import lombok.Getter;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * request包装，让request的请求体可以被多次读取
 *
 * @author jie
 * @version 1.0 2025-02-12
 */
@Getter
public class CustomizeRequestWrapper extends HttpServletRequestWrapper {

    // 缓存请求体
    private final String requestBody;

    public CustomizeRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        requestBody = InputStreamUtil.inputStreamConvertString(request.getInputStream());
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        ByteArrayInputStream byteArrayInputStream =
                new ByteArrayInputStream(requestBody.getBytes(StandardCharsets.UTF_8));
        return new ServletInputStream() {
            @Override
            public int read() {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {

            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }
}
